import { View, Image, Text, ScrollView } from '@tarojs/components'
import PageContainer from '@/components/PageContainer'
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import i18n from 'i18n-js';
import { useStores } from '@/hooks';
import { observer } from 'mobx-react-lite';
import { useMount } from '@/hooks/useMount';
import { toJS } from 'mobx';
import { getItemForPk, getProductName } from '@/config/product';
import { getFAQ } from '@/services/faq';
import { useStatePlus } from '@/hooks/useStatePlus';
import { ConfigProvider, Tabs } from '@taroify/core';
import ListItem from '@/components/ListItem';
import Taro from '@tarojs/taro';

const bgImage = 'https://xbgroup-1251025085.cos.ap-guangzhou.myqcloud.com/cybertron/users/375869/media/help_center_bg_1667446444972.png';

interface IState {
  tabList: IFAQ[];
  tabContentList: IFAQ[][];
  deviceList: IDevice[];
  icon: string[];
  devicesName: string[]
}

const fakeArr = new Array(4).fill(0)

const HelpCenterScreen = () => {
  const styles = dstyles.useDynamicStyle();
  const [state, setState] = useStatePlus<IState>({
    tabList: [],
    tabContentList: [],
    deviceList: [],
    icon: [],
    devicesName: []
  })

  const { deviceList, language, deviceDetail } = useStores()

  useMount(async() => {
    const onlyDevice: IDevice[] = [];
    toJS(deviceList.data).map((i) => {
      const ishas = onlyDevice.findIndex((device) => {
        return device.productKey === i.productKey;
      });
      if (ishas == -1) {
        onlyDevice.push(i);
      }
    });
    const productIcon = onlyDevice.map((item) => {
      return getItemForPk(item.productKey).icon;
    });
    const devicesName = onlyDevice.map((item) => {
      return getProductName(item.productKey, language.key);
    });
    const lang = language.key;
    const res = await getFAQ(lang);
    if (res.success) {
      const list = res.data.filter((i) => {
        return i.question !== '';
      });
      // this.setState({ titleList: list });
      setState({ tabList: list })
      console.log('list',list)
      const promises = list.map((item) => {
        return getFAQ(lang, `parent_id=${item.id}`);
      });

      Promise.all(promises).then((res) => {
        const l: IFAQ[][] = [];
        res.map((item, index) => {
          const questions = item.data.filter((i) => {
            return i.question !== '';
          });
          if (item.success) {
            l.push(questions);
          }
        });
        setState({ tabContentList: l })
        console.log('queryList', l)
      });
      console.log("first", onlyDevice, productIcon, devicesName)
      setState({ deviceList: onlyDevice, icon: productIcon, devicesName });

    }
  })

  const goToFAQ = (title: string, faq: IFAQ) => () => {
    console.log('goToFAQgoToFAQ', title, faq)
    deviceDetail.setFAQDetail(faq);
    Taro.navigateTo({ url: `/pages/FAQ/index?title=${title}` })
  }

  const goToDeviceHelp = (device: IDevice, deviceName: string) => () => {
    deviceDetail.updateDeviceDetail(device);
    Taro.navigateTo({ url: `/pages/deviceHelp/index?title=${deviceName}` });
  }

  const renderTabsPane = () => {
    return fakeArr.map((_, index) => {
      const curTab = state.tabList[index];
      return <Tabs.TabPane style={{ minHeight: '500px' }} key={curTab?.id} title={curTab?.question}>
        {
          state.tabContentList[index]?.map(content => {
            return <ListItem key={content.id} arrow onPress={goToFAQ(curTab.question, content)}>{content.question}</ListItem>
          })
        }
      </Tabs.TabPane>
    })
  }

  return (
    <PageContainer title={i18n.t('HELP_CENTER')}>
      <ScrollView scrollY style={{height: '100%'}}>
        <View style={styles.header}>
          <Image src={bgImage} style={styles.bg} />
          <View style={styles.title}>
            <Text>{i18n.t('HELLO')}</Text>
            <Text>{i18n.t('NEED_ANY_HELP')}</Text>
          </View>
        </View>
        <ConfigProvider theme={{
          tabsActiveColor: DynamicColors.tintColor.value,
          tabsLineWidth: '70%'
        }}
        >
        <Tabs sticky animated  swipeable>
          <Tabs.TabPane title={i18n.t('MY_DEVICE')} style={{minHeight: '500px'}}>
            {
              state.deviceList.map((item, index) => {
                const deviceName = state.devicesName[index]
                return <ListItem key={item.did} icon={<Image style={styles.icon} src={state.icon[index]} />} onPress={goToDeviceHelp(item, deviceName)}>{deviceName}</ListItem>
              })
            }
          </Tabs.TabPane>
          {renderTabsPane()}
        </Tabs>
        </ConfigProvider>
      </ScrollView>
    </PageContainer>
  )
}

const dstyles = GStyleSheet.create({
  header: {
    position: 'relative',
    fontSize: 0
  },
  bg: {
    height: '150px',
    width: '100%',
  },
  title: {
    position: 'absolute',
    fontSize: 24,
    left: 20,
    bottom: 20,
    display: 'flex',
    flexDirection: 'column'
  },
  icon: {
    width: 20,
    height: 20
  }
});

export default observer(HelpCenterScreen)
